package institution

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func FindOneInstitution(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) (*Institution, error) {
	result := new(Institution)
	err := result.GetCollection().FindOne(ctx, filter, opts...).Decode(result)
	if err != nil {
		return nil, err
	}
	return result, err
}

func decodeInstitutionCursor(ctx context.Context, cursor *mongo.Cursor) (InstitutionList *[]Institution, err error) {
	list := &[]Institution{}
	err = cursor.All(ctx, list)
	if err != nil {
		return nil, err
	}
	return list, err
}

func QueryManyInstitution(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (result *[]Institution, err error) {
	cursor, err := (&Institution{}).GetCollection().Find(ctx, filter, opts...)
	if err != nil {
		return nil, err
	}
	result, err = decodeInstitutionCursor(ctx, cursor)
	return result, err
}

func (inst *Institution) FindByID(ctx context.Context, id any, opts ...*options.FindOneOptions) error {
	return inst.FindLastOne(ctx, &bson.D{{"_id", id}}, opts...)
}

// FindLastOne /* 查找单个 */
func (inst *Institution) FindLastOne(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) error {
	_opt := make([]*options.FindOneOptions, 0)
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	_opt = append(_opt, options.FindOne().SetSort(bson.D{{"_id", -1}}))
	return inst.GetCollection().FindOne(ctx, *filter, _opt...).Decode(inst)
}

type InstitutionList []Institution

// FindMany /* 查找d多个 */
func (inst *InstitutionList) FindMany(ctx context.Context, filter *bson.D, opts ...*options.FindOptions) error {
	_opt := make([]*options.FindOptions, 0)
	_opt = append(_opt, options.Find().SetSort(bson.D{{"_id", -1}}))
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	cursor, err := (&Institution{}).GetCollection().Find(ctx, *filter, _opt...)
	if err != nil {
		return err
	}
	return cursor.All(ctx, inst)
}

// / 当前只有一个考试机构
func GetCurrentActiveInstitution(ctx context.Context) (institution *Institution, err error) {
	institution = &Institution{}
	err = institution.FindLastOne(ctx, &bson.D{})
	return
}
